package com.zhl.dao.impl;

import com.zhl.dao.UserDao;
import com.zhl.entity.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

/**
 * 用户持久层  dao的实现层
 */
@Repository("userDao")
public class UserDaoImpl implements UserDao {

    @Autowired
    private QueryRunner queryRunner;


    @Override
    public List<User> findAllUser() {

        try {
            return queryRunner.query("select * from user",new BeanListHandler<User>(User.class));
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public User findOne(Integer id) {

        try {
            return queryRunner.query("select * from user where id = ?",new BeanHandler<User>(User.class),id);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void addUser(User user) {
        try {
            queryRunner.update("insert into user(username,password) values(?,?)",user.getUsername(),user.getPassword());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteUser(Integer id) {
        try {
            queryRunner.update("delete from user where id = ?",id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateUser(User user) {
        try {
            queryRunner.update("update user set username=?,password=? where id=?",user.getUsername(),user.getPassword(),user.getId());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
